<script setup>
import { ref, onMounted, computed } from 'vue'
import { sessionApi, pageLogsApi, treeMenusApi, selUsersApi } from '@/commons/api'
import routes from '@/commons/router'
import Pager from '@/components/pager/Pager.vue'
import Msg from '@/components/message'
import TreeSel from '@/components/cascader/TreeSel.vue'
import Selector from '@/components/select/Selector.vue'
import Datepicker from '@vuepic/vue-datepicker'
import '@vuepic/vue-datepicker/dist/main.css'
import { formatDate, formatDateRange } from '@/commons/filter'
import Loader from '@/components/loader/Loader.vue'

const loadShow = ref(false)

// 界面挂载前处理
onMounted(() => {
  // 获取用户会话信息
  checkAuth()
})

// checkAuth 获取权限
const checkAuth = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    if (res.code === import.meta.env.VITE_SUCCESS_CODE) {
      await list(0, 1)
      await selMenu()
      await selUser()
    } else {
      loadShow.value = false
      localStorage.removeItem("token")
      Msg({ kind: 'error', txt: res.msg })
      routes.replace('/login')
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const dates = ref([])
const schObj = {
  userId: '',
  nickName: '',
  usname: '',
  menuId: '',
  menuName: '',
  menuCode: '',
  kind: 0,
  kindName: '',
  kindCode: '',
  beginDate: 0,
  endDate: 0,
  offset: 0,
  limit: 20
}
const schRef = ref(schObj)
const total = ref(0)
const curPage = ref(1)
const logList = ref([])
const hasData = ref(false)
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  schRef.value.beginDate = dates.value && dates.value.length===2 ? dates.value[0].getTime()/1000 : 0
  schRef.value.endDate = dates.value && dates.value.length===2 ? dates.value[1].getTime()/1000 : 0
  const res = await pageLogsApi(schRef.value)
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    hasData.value = true
    total.value = res.data.total
    logList.value = res.data.list
  }
}

// search 显示隐藏筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    userId: '',
    nickName: '',
    usname: '',
    menuId: '',
    menuName: '',
    menuCode: '',
    kind: 0,
    kindName: '',
    kindCode: '',
    beginDate: 0,
    endDate: 0,
    offset: 0,
    limit: 20
  }
  list(0, 1)
  dates.value = null
}

// selMenu 获取菜单下拉列表
const menuList = ref([])
const selMenu = async () => {
  const res = await treeMenusApi()
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    menuList.value = res.data
  }
}

// selUser 获取用户下拉列表
const userList = ref([])
const selUser = async (keywords) => {
  userList.value = []
  const res = await selUsersApi({ keywords: keywords, deptId: '', limit: 20, offset: 0 })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    userList.value = res.data.list
    userList.value.forEach(item => {
      item.selId = item.userId
      item.selName = item.nickName
      item.selCode = item.deptName
    })
  }
}

const selByKey = (keywords) => {
  selUser(keywords)
}

const setValue = (item, kind) => {
  switch(kind) {
    case 1:
      schRef.value.menuId = item.selId
      schRef.value.menuName = item.selName
      schRef.value.menuCode = item.selCode
      break
    case 2:
      schRef.value.userId = item.selId
      schRef.value.nickName = item.selName
      schRef.value.usname = item.selCode
      break
    case 3:
      schRef.value.kind = item.selId
      schRef.value.kindName = item.selName
      schRef.value.kindCode = item.selCode
      break
  }
}

// fmtDate 时间戳转时间
const fmtDate = computed(() => {
  return (time, kind) => {
    let date = new Date(time*1000)
    return formatDate(date, kind)
  }
})

const kindList = ref([
  {selId: 1, selName: '新增', selCode: '101', chhed: false},
  {selId: 2, selName: '删除', selCode: '102', chhed: false},
  {selId: 3, selName: '修改', selCode: '103', chhed: false},
  {selId: 4, selName: '启用', selCode: '104', chhed: false},
  {selId: 5, selName: '停用', selCode: '105', chhed: false},
  {selId: 6, selName: '登录', selCode: '106', chhed: false}
])

// fmtKind 状态转码
const fmtKind = computed(() => {
  return (kind) => {
    let str = ''
    switch (kind) {
      case 1:
        str = '新增'
        break;
      case 2:
        str = '删除'
        break;
      case 3:
        str = '修改'
        break;
      case 4:
        str = '启用'
        break;
      case 5:
        str = '停用'
        break;
      case 6:
        str = '登录'
        break;
      default:
        str = '其它'-kind
        break
    }
    return str
  }
})
</script>

<template>
  <div class="a">
    <div class="b">
      <div class="c">
        <div class="btn-r mr15" title="筛选" @click="search"><i class="iconfont">&#xea49;</i></div>
        <div class="btn-r mr15" title="刷新" @click="list(0, 1)"><i class="iconfont">&#xea8c;</i></div>
      </div>
      <div class="d"><i class="iconfont">&#xeaaa;</i> 当前位置：工作台 > 系统管理 > 操作日志</div>
    </div>
    <div v-show="schShow" class="e">
      <div class="mr15 mt10"><tree-sel :tree-list="menuList" :kind="1" :inboxed="true" :curName="schRef.menuName!=='' ? schRef.menuName+'['+schRef.menuCode+']' : ''" pre-name="菜单" @setValue="setValue" /></div>
      <div class="mr15 mt10"><selector :kind="2" :sel-list="userList" :inboxed="true" :curName="schRef.nickName!=='' ? schRef.nickName+'['+schRef.usname+']' : ''" pre-name="用户" @setValue="setValue" @selByKey="selByKey" /></div>
      <div class="mr15 mt10"><selector :kind="3" :sel-list="kindList" :inboxed="true" :curName="schRef.kindName!=='' ? schRef.kindName+'['+schRef.kindCode+']' : ''" pre-name="操作" @setValue="setValue" /></div>
      <div class="mr15 mt10"><datepicker v-model="dates" range locale="zh-CN" :format="formatDateRange" style="width: 250px;" placeholder="请选择起止时间" /></div>
      <div class="mr15 mt10"><input type="text" v-model="schRef.keywords" maxlength="30" placeholder="请输入关键字" class="sch-ipt" /></div>
      <div class="f mt10">
        <div class="btn-pi mr15" title="搜索" @click="list(0, 1)"><i class="iconfont">&#xea8e;</i> 搜索</div>
        <div class="btn-d" title="重置" @click="clrSch"><i class="iconfont">&#xea4f;</i> 重置</div>
      </div>
    </div>
    <div v-if="hasData">
      <table>
        <tbody>
          <tr>
            <th style="width: 30%;">用户</th>
            <th style="width: 20%;">菜单</th>
            <th style="width: 15%;">操作</th>
            <th style="width: 15%;">IP地址</th>
            <th style="width: 20%;">时间</th>
          </tr>
          <tr v-for="log in logList" :key="log.logId" class="tr-style">
            <td class="txt-center">{{log.logUser}}</td>
            <td class="txt-center">{{log.menuName}}</td>
            <td class="txt-center">{{fmtKind(log.kind)}}</td>
            <td class="txt-center">{{log.ipAddr}}</td>
            <td class="txt-center">{{fmtDate(log.addTime, 2)}}</td>
          </tr>
        </tbody>
      </table>
      <Pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.a {padding: 10px;}
.b {padding: 0 20px 10px 20px; display: flex; display: -webkit-flex;}
.c {display: inline-flex; display: -webkit-inline-flex;}
.d {flex-grow: 1; text-align: right; padding-top: 10px; color: #666;}
.e {border: 1px dashed #DDD; padding: 5px 15px 15px 15px; display: flex; display: -webkit-flex; flex-wrap: wrap; margin-bottom: 10px;}
.f {display: inline-flex; display: -webkit-inline-flex;}
</style>